#include <chrono>
#include <memory>
#include <string>

#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"

using namespace std::chrono_literals;

class PublisherNode : public rclcpp::Node
{
   public:
    PublisherNode() : Node("publisher_node")
    {
        // 声明参数
        this->declare_parameter("publish_frequency", 1.0);
        this->declare_parameter("message_prefix", "Hello");

        // 获取参数
        double frequency = this->get_parameter("publish_frequency").as_double();
        std::string prefix = this->get_parameter("message_prefix").as_string();

        // 创建发布者
        publisher_ = this->create_publisher<std_msgs::msg::String>("topic", 10);

        // 创建定时器
        timer_ = this->create_wall_timer(std::chrono::milliseconds(static_cast<int>(1000.0 / frequency)),
                                         [this, prefix]() -> void {
                                             auto message = std_msgs::msg::String();
                                             message.data = prefix + " from publisher_node " + std::to_string(count_++);
                                             RCLCPP_INFO(this->get_logger(), "Publishing: '%s'", message.data.c_str());
                                             publisher_->publish(message);
                                         });

        RCLCPP_INFO(this->get_logger(), "Publisher node started with frequency: %.1f Hz", frequency);
    }

   private:
    rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_;
    rclcpp::TimerBase::SharedPtr timer_;
    int count_ = 0;
};

int main(int argc, char *argv[])
{
    rclcpp::init(argc, argv);
    rclcpp::spin(std::make_shared<PublisherNode>());
    rclcpp::shutdown();
    return 0;
}
